<template>
	<div>
		<CustomDialog
			:title="state.dialog.title"
			v-model:visible="state.dialog.isShowDialog"
			dialogWidth="900px"
			@close="closeDialog"
			:dialogFooterBtn="true"
		>
			<!-- <el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog" width="900px"> -->
			<el-form ref="discountDialogFormRef" :model="state.ruleForm" size="default" label-width="120px">
				<el-form-item label="活动名称" prop="groupName" :rules="{ required: true, message: '活动名称不能为空', trigger: 'blue' }">
					<el-input v-model="state.ruleForm.groupName" placeholder="请输入活动名称" clearable></el-input>
				</el-form-item>

				<el-form-item label="活动时间" prop="activityTime" :rules="{ required: true, message: '活动时间不能为空', trigger: 'blue' }">
					<el-date-picker
						v-model="state.ruleForm.activityTime"
						type="datetimerange"
						range-separator="至"
						start-placeholder="开始时间"
						end-placeholder="结束时间"
					/>
				</el-form-item>

				<el-form-item label="预热时间" prop="groupPreTime" :rules="{ required: true, message: '活动预热时间不能为空', trigger: 'blue' }">
					<el-date-picker v-model="state.ruleForm.groupPreTime" type="datetime" placeholder="请选择预热时间" />
				</el-form-item>

				<el-form-item label="拼团解散时间" prop="groupDisbandHours" :rules="{ required: true, message: '拼团解散时间不能为空', trigger: 'blue' }">
					<el-input v-model="state.ruleForm.groupDisbandHours" placeholder="请输入解散时间" clearable>
						<template #append> 小时</template>
					</el-input>
				</el-form-item>

				<el-form-item label="成团人数" prop="finishPurchaseCount" :rules="{ required: true, message: '成团人数不能为空', trigger: 'blue' }">
					<el-input v-model="state.ruleForm.finishPurchaseCount" placeholder="请输入成团人数" clearable type="number" min="2">
						<template #append> 人</template>
					</el-input>
				</el-form-item>

				<el-form-item label="单独购买" prop="groupPreTime">
					<el-switch
						v-model="state.ruleForm.purchaseSep"
						inline-prompt
						active-text="允许"
						inactive-text="不允许"
						:active-value="1"
						:inactive-value="0"
					/>
				</el-form-item>

				<el-form-item label="虚拟成团" prop="virtualGroup">
					<el-switch
						v-model="state.ruleForm.virtualGroup"
						:disabled="state.virtualGroupTypeDisabled"
						inline-prompt
						active-text="允许"
						inactive-text="不允许"
						:active-value="1"
						:inactive-value="0"
					/>
					<div class="tip">
						开启虚拟成团后，在拼团有效期内人数不够的团，系统会虚拟用户凑满人数，使拼团成功。
						虚拟的用户不生成订单，只需对真实买家发货。(请在资料管理中添加足够数量的虚拟用户，否则虚拟成团不会成功)
					</div>
				</el-form-item>

				<el-form-item v-if="state.ruleForm.virtualGroup == 1">
					<div class="acitivty-rule">
						<!-- <el-form label-position="left"> -->
						<div class="activity-rule-content">
							<el-form-item>
								<el-row :gutter="10">
									<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
										<el-form-item
											label="最多虚拟人数"
											prop="virtualFinish.virtualPersonCount"
											:rules="{ required: true, message: '最多虚拟人数不能为空', trigger: 'blue' }"
										>
											<el-input v-model="state.ruleForm.virtualFinish.virtualPersonCount" type="number" min="1">
												<template #append>
													<div>人</div>
												</template>
											</el-input>
										</el-form-item>
									</el-col>
									<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
										<div class="tip">单团最多虚拟人数的名额限制，不填时，不限制名额</div>
									</el-col>

									<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
										<el-form-item
											label="虚拟成团时间"
											prop="virtualFinish.virtualHours"
											:rules="{ required: true, message: '虚拟成团时间不能为空', trigger: 'blue' }"
										>
											<el-input v-model="state.ruleForm.virtualFinish.virtualHours" type="number" min="1">
												<template #append>
													<div>小时</div>
												</template>
											</el-input>
										</el-form-item>
									</el-col>
									<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
										<div class="tip">将会在拼团解散时间之前尝试虚拟成团</div>
									</el-col>
								</el-row>
							</el-form-item>
						</div>
						<!-- </el-form> -->
					</div>
				</el-form-item>

				<el-form-item label="参团卡显示" prop="groupPreTime">
					<el-switch
						v-model="state.ruleForm.groupCardShow"
						inline-prompt
						active-text="开启"
						inactive-text="关闭"
						:active-value="1"
						:inactive-value="0"
					/>
					<div class="ctc">开启参团卡显示后，商品详情页显示未成团的团列表，买家可以直接选择一个参团。</div>
				</el-form-item>

				<el-form-item label="拼团销量展示" prop="groupPreTime">
					<el-radio-group v-model="state.ruleForm.salesShowType">
						<!-- works when <2.6.0, deprecated act as value when >=3.0.0 -->
						<el-radio :label="0">真实活动销量</el-radio>
						<el-radio :label="1">商品总销量</el-radio>
						<div class="ctc">商品总销量包含虚拟销量</div>
					</el-radio-group>
				</el-form-item>

				<el-form-item label="是否包邮" prop="groupPreTime">
					<el-switch
						v-model="state.ruleForm.freeShipping"
						inline-prompt
						active-text="包邮"
						inactive-text="不包邮"
						:active-value="1"
						:inactive-value="0"
					/>
				</el-form-item>

				<el-form-item label="团长优惠" prop="groupLeaderDiscount">
					<el-switch
						v-model="state.ruleForm.groupLeaderDiscount"
						inline-prompt
						active-text="不优惠"
						inactive-text="优惠"
						:active-value="1"
						:inactive-value="0"
					/>
				</el-form-item>

				<el-form-item label="限购数量" prop="limitPurchaseCounts" :rules="{ required: true, message: '限购数量不能为空', trigger: 'blue' }">
					<el-input v-model="state.ruleForm.limitPurchaseCounts" placeholder="请输入限购数量" type="number" min="1" clearable>
						<template #append> 件</template>
					</el-input>
				</el-form-item>

				<el-form-item label="退款方式" prop="groupPreTime">
					<div>
						<el-radio-group v-model="state.ruleForm.refundMethod">
							<el-radio :label="0">原路返回</el-radio>
							<el-radio :label="1">返回到余额</el-radio>
						</el-radio-group>
						<div class="tip">拼团失败解散时，默认退款方式</div>
					</div>
				</el-form-item>

				<el-form-item label="订单支付时间" prop="paymentTimes" :rules="{ required: true, message: '订单支付时间不能为空', trigger: 'blue' }">
					<el-input v-model="state.ruleForm.paymentTimes" placeholder="请输入订单支付时间" clearable type="number" min="1">
						<template #append> 分钟</template>
					</el-input>
				</el-form-item>

				<el-form-item label="活动说明" prop="activityDesc">
					<el-input v-model="state.ruleForm.activityDescTitle" placeholder="请选择活动说明">
						<template #append>
							<div class="cursor-pointer" @click="openRichTextDialog">选择活动说明</div>
						</template>
					</el-input>
				</el-form-item>

				<div class="activity-item">
					<el-form-item label="活动商品">
						<el-button type="primary" link @click="addItem"> +添加商品</el-button>
					</el-form-item>
					<el-form-item>
						<div class="item-content">
							<div v-if="state.items.length > 0" class="flex item-header">
								<div class="content">商品信息</div>
								<div class="oper">设置</div>
								<div class="oper">操作</div>
							</div>
							<div>
								<div class="flex item-body" v-for="(item, index) in state.items">
									<div class="content flex">
										<div class="goods-img">
											<img :src="STATIC_URL + item.image" alt="" class="goods-img" />
										</div>
										<div class="goods-content">
											<div class="goods-title cursor-pointer" :title="item.title">{{ item.title }}</div>
											<div class="goods-price">{{ item.price }}元</div>
										</div>
									</div>
									<div class="oper">
										<el-button type="primary" link @click="setItem(index)"> 设置商品</el-button>
									</div>

									<div class="oper">
										<el-button type="danger" link @click="removeItem(index)"> 移除</el-button>
									</div>
								</div>
							</div>
						</div>
					</el-form-item>
				</div>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" size="default">取 消</el-button>
					<el-button type="primary" @click="onSubmit(discountDialogFormRef)" size="default">{{ state.dialog.submitTxt }}</el-button>
				</span>
			</template>
		</CustomDialog>
		<!-- </el-dialog> -->
		<ItemDialog ref="ItemChoiceRef" @choice="choiceItem"></ItemDialog>
		<ItemSetDialog ref="ItemSetDialogRef"></ItemSetDialog>
		<ChoiceRichTextDialog ref="ChoiceRichTextDialogRef" @choice="choiceRichText"></ChoiceRichTextDialog>
	</div>
</template>

<script setup lang="ts">
import { reactive, ref, defineAsyncComponent } from 'vue';
import { type FormInstance, type FormRules } from 'element-plus';
import msg from '/@/utils/messageUtils';
import { STATIC_URL } from '/@/utils/config';

import { GroupApi } from '/@/api/shop/group/index';
import _ from 'lodash';
import messageUtils from '/@/utils/messageUtils';
const ChoiceRichTextDialog = defineAsyncComponent(() => import('/@/views/shop/data/richtext/choice/index.vue'));
const ChoiceRichTextDialogRef = ref();
const ItemDialog = defineAsyncComponent(() => import('/@/views/goods/goods/choice/index.vue'));
const ItemSetDialog = defineAsyncComponent(() => import('./item_set_dialog.vue'));
const ItemChoiceRef = ref();
const ItemSetDialogRef = ref();
const discountDialogFormRef = ref();
const emit = defineEmits(['refresh']);
const state = reactive({
	ruleForm: {
		id: '',
		activityTime: [],
		groupName: '',
		startTime: '',
		endTime: '',
		groupPreTime: '',
		groupDisbandHours: 0,
		finishPurchaseCount: 0,
		limitPurchaseCounts: 0,
		groupCardShow: 0,
		freeShipping: 0,
		groupLeaderDiscount: 0,
		paymentTimes: 0,
		refundMethod: 0,
		salesShowType: 0,
		virtualGroup: 0,
		purchaseSep: 0,
		activityType: 1,
		discountType: 0,
		activityDescId: '',
		activityDescTitle: '',
		virtualFinish: {
			virtualPersonCount: 0,
			virtualHours: 0,
		},
	},
	virtualGroupTypeDisabled: false,
	items: [] as any,
	dialog: {
		isShowDialog: false,
		type: '',
		title: '',
		submitTxt: '',
	},
});

const rules = reactive<FormRules>({
	activityName: [{ required: true, message: '请输入活动名称', trigger: 'blur' }],
	activityTime: [{ required: true, message: '请选择活动时间 ', trigger: 'blur' }],
});

const onCancel = () => {
	closeDialog();
};

const openRichTextDialog = () => {
	ChoiceRichTextDialogRef.value.openDialog();
};

const choiceRichText = (choiceRichText: ChoiceRichText) => {
	console.log('choiceRichText: ', choiceRichText);
	state.ruleForm.activityDescId = choiceRichText.id;
	state.ruleForm.activityDescTitle = choiceRichText.title;
};

const choiceItem = (choiceGoodsItems: ChoiceGoodsItem[]) => {
	console.log('choiceGoodsItem: ', choiceGoodsItems);
	choiceGoodsItems.forEach((choiceGoodsItem) => {
		state.items.push({
			goodsId: choiceGoodsItem.id,
			image: choiceGoodsItem.image,
			title: choiceGoodsItem.title,
			subTitle: choiceGoodsItem.subTitle,
			price: choiceGoodsItem.price,
			originalPrice: choiceGoodsItem.originalPrice,
			stock: choiceGoodsItem.stock,
			sales: choiceGoodsItem.sales,
			itemProps: [],
		});
	});
};

const setItem = (index: number) => {
	console.log('index: ', index);
	ItemSetDialogRef.value.openDialog(state.items[index], state.ruleForm.groupLeaderDiscount);
};

const removeItem = (index: number) => {
	state.items.splice(index, 1);
};

const addItem = () => {
	ItemChoiceRef.value.openDialog();
};
// 关闭弹窗
const closeDialog = () => {
	console.log('关闭窗口');
	state.dialog.isShowDialog = false;
	clearArraysContent();
};

const checkGoodsSeting = () => {
	const check = _.every(state.items, (e) => {
		if (_.isEmpty(e.itemProps)) {
			messageUtils().error(`商品-[${e.title}]-没有进行设置信息,请全部设置信息后再提交`);
			return false;
		}
		return true;
	});
	return check;
};

const onSubmit = async (formEl: FormInstance | undefined) => {
	const activityTime = state.ruleForm.activityTime;
	console.log('activityTime: ', activityTime);
	console.log('startTime:  ', activityTime[0]);
	if (!formEl) return;
	await formEl.validate(async (valid) => {
		if (valid) {
			if (!checkGoodsSeting()) {
				return;
			}
			try {
				if (state.dialog.type === 'add') {
					await GroupApi().create({
						groupName: state.ruleForm.groupName,
						groupStartTime: activityTime[0].getTime(),
						groupEndTime: activityTime[1].getTime(),
						groupPreTime: state.ruleForm.groupPreTime.getTime(),
						groupDisbandHours: state.ruleForm.groupDisbandHours,
						finishPurchaseCount: state.ruleForm.finishPurchaseCount,
						limitPurchaseCounts: state.ruleForm.limitPurchaseCounts,
						purchaseSep: state.ruleForm.purchaseSep,
						virtualGroup: state.ruleForm.virtualGroup,
						groupCardShow: state.ruleForm.groupCardShow,
						freeShipping: state.ruleForm.freeShipping,
						groupLeaderDiscount: state.ruleForm.groupLeaderDiscount,
						salesShowType: state.ruleForm.salesShowType,
						refundMethod: state.ruleForm.refundMethod,
						paymentTimes: state.ruleForm.paymentTimes,
						virtualFinish: state.ruleForm.virtualFinish,
						sharingItems: state.items,
						activityDescId: state.ruleForm.activityDescId,
						activityDescTitle: state.ruleForm.activityDescTitle,
						items: state.items,
					});
				} else {
					await GroupApi().update({
						id: state.ruleForm.id,
						groupName: state.ruleForm.groupName,
						groupStartTime: resolveTime(activityTime[0]),
						groupEndTime: resolveTime(activityTime[1]),
						groupPreTime: resolveTime(state.ruleForm.groupPreTime),
						groupDisbandHours: state.ruleForm.groupDisbandHours,
						finishPurchaseCount: state.ruleForm.finishPurchaseCount,
						limitPurchaseCounts: state.ruleForm.limitPurchaseCounts,
						purchaseSep: state.ruleForm.purchaseSep,
						virtualGroup: state.ruleForm.virtualGroup,
						groupCardShow: state.ruleForm.groupCardShow,
						freeShipping: state.ruleForm.freeShipping,
						groupLeaderDiscount: state.ruleForm.groupLeaderDiscount,
						salesShowType: state.ruleForm.salesShowType,
						refundMethod: state.ruleForm.refundMethod,
						paymentTimes: state.ruleForm.paymentTimes,
						virtualFinish: state.ruleForm.virtualFinish,
						sharingItems: state.items,
						activityDescId: state.ruleForm.activityDescId,
						activityDescTitle: state.ruleForm.activityDescTitle,
						items: state.items,
					});
				}
				msg().success('操作成功');
				closeDialog();
				emit('refresh');
			} catch (e) {
				console.log('e: ', e);
				// msg().error('操作失败');
			}
		}
	});
};

const openDialog = async (type: string, id: string) => {
	if (type === 'edit') {
		state.virtualGroupTypeDisabled = true;
		state.dialog.title = '修改平团活动';
		state.dialog.submitTxt = '修 改';
		state.dialog.type = 'edit';
		state.ruleForm.id = id;
		console.log('id: ', id);
		const { data } = await GroupApi().view(id);
		state.ruleForm.id = id;
		state.ruleForm.groupName = data.groupName;
		state.ruleForm.groupPreTime = data.groupPreTime;
		state.ruleForm.activityTime = [data.groupStartTime, data.groupEndTime];
		state.ruleForm.groupDisbandHours = data.groupDisbandHours;
		state.ruleForm.limitPurchaseCounts = data.limitPurchaseCounts;
		state.ruleForm.finishPurchaseCount = data.finishPurchaseCount;
		state.ruleForm.groupCardShow = data.groupCardShow;
		state.ruleForm.freeShipping = data.freeShipping;

		state.ruleForm.groupLeaderDiscount = data.groupLeaderDiscount;
		state.ruleForm.paymentTimes = data.paymentTimes;
		state.ruleForm.refundMethod = data.refundMethod;
		state.ruleForm.salesShowType = data.salesShowType;

		state.ruleForm.virtualGroup = data.virtualGroup;
		state.ruleForm.purchaseSep = data.purchaseSep;
		state.ruleForm.activityType = data.activityType;
		state.ruleForm.discountType = data.discountType;
		state.ruleForm.salesShowType = data.salesShowType;
		state.ruleForm.virtualFinish = data.groupSharingVirtualFinishVO;
		state.ruleForm.activityDescId = data.activityDescId;
		state.ruleForm.activityDescTitle = data.activityDescTitle;
		state.items = data.groupItems;
	} else {
		state.virtualGroupTypeDisabled = false;
		state.dialog.title = '新增拼团活动';
		state.dialog.submitTxt = '新 增';
		state.dialog.type = type;
		state.ruleForm.activityTime = [];
	}
	state.dialog.isShowDialog = true;
};

const resolveTime = (time: any) => {
	const contentType = typeof time;

	if (contentType == 'string') {
		console.log('time: ', time, ' is string');
		return new Date(time).getTime();
	}
	return time.getTime();
};

const clearArraysContent = () => {
	state.ruleForm.activityTime = [];
	state.ruleForm.groupName = '';
	state.ruleForm.groupPreTime = '';
	state.ruleForm.groupDisbandHours = 0;
	state.ruleForm.finishPurchaseCount = 0;
	state.ruleForm.limitPurchaseCounts = 0;
	state.ruleForm.groupCardShow = 0;
	state.ruleForm.freeShipping = 0;
	state.ruleForm.groupLeaderDiscount = 0;
	state.ruleForm.paymentTimes = 0;
	state.ruleForm.refundMethod = 0;
	state.ruleForm.salesShowType = 0;
	state.ruleForm.virtualGroup = 0;
	state.ruleForm.purchaseSep = 0;
	state.ruleForm.activityType = 1;
	state.ruleForm.discountType = 0;
	state.ruleForm.activityDescId = '';
	state.ruleForm.activityDescTitle = '';
	state.ruleForm.virtualFinish = {
		virtualPersonCount: 0,
		virtualHours: 0,
	};
	state.items = [];
};
defineExpose({ openDialog });
</script>

<style scoped>
.item-content {
	width: 400px;
}

.exec-width {
	width: 250px;
	margin-left: 10px;
}

.item-header {
	background-color: rgba(223, 230, 233, 1);
}

.item-body {
	margin-top: 10px;
}

.content {
	flex: 1;
}

.oper {
	width: 60px;
	margin-left: 5px;
}

.goods-img {
	width: 50px;
	height: 50px;
}

.goods-content {
	margin-left: 10px;
	flex: 1;

	.goods-title {
		font-size: 14px;
		height: 20px;
		line-height: 20px;
		overflow: hidden;
		text-overflow: ellipsis;
		/* white-space: nowrap; */
		/* text-overflow: ellipsis; */
		display: -webkit-box;
		-webkit-line-clamp: 1;
		-webkit-box-orient: vertical;
		padding-right: 5px;
	}

	.goods-price {
		font-size: 12px;
		height: 20px;
		line-height: 40px;
		color: rgba(255, 118, 117, 1);
	}
}

.tip {
	width: fit-content;
	line-height: 16px;
	font-size: 12px;
	color: #8c8c8c;
}

.ctc {
	display: inline-block;
	color: #8c8c8c;
	line-height: 16px;
	font-size: 12px;
	margin-left: 5px;
}
</style>
